﻿using System;
using System.Collections.Generic;
using System.Text;
using NFinal.Action;
using System.IO;
using System.Threading.Tasks;

namespace NFinal
{
    public abstract class FileStreamResult : FileResult
    {
        public Stream Stream { get; set; }
        public FileStreamResult(Stream stream,string contentType):base(contentType)
        {
            this.ContentType = contentType;
            this.Stream = stream;
        }

        public override async Task ExecuteResultAsync<TContext, TRequest>(AbstractAction<TContext, TRequest> context)
        {
            context.SetResponseHeader(Constant.HeaderContentType,this.ContentType);
            if (FileDownloadName != null)
            {
                context.SetResponseHeader(Constant.HeaderContentDisposition, "attachment;filename=" + Uri.EscapeUriString(this.FileDownloadName));
            }
            context.SetResponseHeader(Constant.HeaderContentLength, this.Stream.Length.ToString());
            if (this.ContentType?.Length > 0)
            {
                context.contentType = this.ContentType;
            }
            this.Stream.Seek(0, SeekOrigin.Begin);
            byte[] buffer = new byte[512];
            int count = 0;
            while ((count = this.Stream.Read(buffer, 0, 512)) > 0)
            {
                await context.WriteAsync(buffer, 0, count);
            }
        }
    }
}
